package com.example.myutil;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;


public class DateConvert implements Converter<String, Date> {
	
	private static final Logger LOG = LoggerFactory.getLogger(DateConvert.class);

	public static final SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final SimpleDateFormat time_sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	public static final SimpleDateFormat time_sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
	public static final SimpleDateFormat yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd");
	public static final SimpleDateFormat yyyy_MM = new SimpleDateFormat("yyyy-MM");
	public static final SimpleDateFormat yyyy = new SimpleDateFormat("yyyy");
	
    @Override
    public Date convert(String stringDate) {
    	if(MyUtil.isNullString(stringDate)) return null;
    	stringDate = stringDate.trim();
    	
    	Date date = null;
        try {
        	if(MyUtil.isNumeric(stringDate) && stringDate.length() == 13){
        		Long time = Long.valueOf(stringDate);
        		date = DateUtils.getDate(time);
        	}
        	
        	if(date == null)
        		date = DateUtils.str2Date(stringDate, datetimeFormat);
        	
        	if(date == null)
        		date = DateUtils.str2Date(stringDate, time_sdf);
        	
        	if(date == null)
        		date = DateUtils.str2Date(stringDate, time_sdf2);
        	
        	if(date == null)
        		date = DateUtils.str2Date(stringDate, yyyy_MM_dd);
        	
        	if(date == null)
        		date = DateUtils.str2Date(stringDate, yyyy_MM);
        	
        	if(date == null)
        		date = DateUtils.str2Date(stringDate, yyyy);
        	
        } catch (Exception e) {
            LOG.error("", e);
            date = null;
        }
        return date;
    }
}
